import {
  BadRequestException,
  ForbiddenException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { IsNull, Repository } from 'typeorm';
import { CreateCommentDto } from './dto/create-comment.dto';
import { User } from 'src/entities/user.entity';
import { Comment } from 'src/entities/comment.entity';
import { PaginationDto } from './dto/pagination.dto';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(Comment)
    private commentRepository: Repository<Comment>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async createComment(
    dto: CreateCommentDto,
    user_id: string,
  ): Promise<Comment> {
    const comment = new Comment();
    comment.content = dto.content;
    comment.videoId = dto.videoId;

    // 获取当前用户
    const user = await this.userRepository.findOne({
      where: [{ id: Number(user_id) }],
    });

    comment.user = user;

    if (dto.parentId) {
      const parentComment = await this.commentRepository.findOne({
        where: { id: dto.parentId },
        relations: ['parent'],
      });

      if (!parentComment) {
        throw new NotFoundException('没有找到父评论');
      }

      // 确保父评论本身没有父级（只允许二级评论）
      if (parentComment.parent) {
        throw new BadRequestException('父级评论不能有父级');
      }

      comment.parent = parentComment;
    }

    if (dto.replyToUserId) {
      const replyToUser = await this.userRepository.findOneBy({
        id: dto.replyToUserId,
      });
      if (!replyToUser) {
        throw new NotFoundException('未找到回复用户');
      }
      comment.replyToUser = replyToUser;
    }

    return this.commentRepository.save(comment);
  }

  async getCommentsByVideo(videoId: number, pagination: PaginationDto) {
    const { page, limit } = pagination;
    const skip = (page - 1) * limit;

    // 首先只查询主评论，不加载关系
    const [comments, total] = await this.commentRepository.findAndCount({
      where: {
        videoId,
        parent: IsNull(),
        deletedAt: IsNull(),
      },
      order: {
        createdAt: 'DESC',
      },
      skip,
      take: limit,
    });
    
    // 然后为这些评论加载回复
    const commentsWithReplies = await Promise.all(
      comments.map(async (comment) => {
        const commentWithRelations = await this.commentRepository.findOne({
          where: { id: comment.id },
          relations: ['user', 'replies', 'replies.user', 'replies.replyToUser'],
        });
        return commentWithRelations;
      })
    );

    return {
      data: commentsWithReplies.map(comment => this.formatComment(comment)),
      meta: {
        currentPage: page,
        itemsPerPage: limit,
        totalItems: total,
        totalPages: Math.ceil(total / limit)
      }
    };
  }

  private formatComment(comment: Comment) {
    return {
      ...comment,
      replies: comment.replies
        .filter(reply => !reply.deletedAt)
        .map(reply => ({
          ...reply,
          replyToUser: reply.replyToUser ? {
            id: reply.replyToUser.id,
            username: reply.replyToUser.username
          } : null
        }))
    };
  }

  async deleteComment(commentId: number, user_id: number) {

    // 获取当前用户
    const user = await this.userRepository.findOne({
      where: [{ id: Number(user_id) }],
    });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }
    const comment = await this.commentRepository.findOne({
      where: { id: commentId },
      relations: ['user']
    });
  
    if (!comment) {
      throw new NotFoundException('评论不存在');
    }
  
    if (comment.user.id !== user.id) {
      throw new ForbiddenException('无权删除该评论');
    }
    
    await this.commentRepository.softDelete(commentId);
  
    // 删除所有子评论
    await this.commentRepository
      .createQueryBuilder()
      .update(Comment)
      .set({ deletedAt: new Date() })
      .where('parent_id = :commentId', { commentId })
      .execute();

    return {
      message: '删除成功'
    };
  }
}
